"use client"
import Link from "next/link"
import { useState, useEffect } from "react"
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react';
export const dynamicParams = true // 允许动态参数
import { useRouter } from 'next/navigation';
import { API_CONFIG } from "../../url"

interface Student {
  id: string
  stuName: string
  stuIdnumber: string
  workplace: string
  stuPhone: string
  teacher: string
  region: string
  city: string
  email: string
}

interface ApiResponse {
  total: number
  list: Student[]
  pageNum: number
  pageSize: number
  pages: number
  isFirstPage: boolean
  isLastPage: boolean
}

function FormContent() {
  const router = useRouter();

  const [students, setStudents] = useState<Student[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(5) // 每页5条数据
  const [total, setTotal] = useState(0)
  const [pages, setPages] = useState(0)

  // 从 localStorage 获取数据
  const [id, setId] = useState<string | null>(null)
  const [undertaker, setUndertaker] = useState<string | null>(null)
  const [parentId, setParentId] = useState<string | null>(null)
  const [token, setToken] = useState<string | null>(null);
  const [showOrderButton, setShowOrderButton] = useState(false);
  const [parentLevel, setParentLevel] = useState<string | null>(null)

  // 搜索参数状态
  const [searchParams, setSearchParams] = useState({
    stuName: '',
    stuIdnumber: '',
    stuPhone: ''
  });

  // 存储当前搜索条件，用于分页时保持搜索状态
  const [currentSearch, setCurrentSearch] = useState<{
    stuName?: string,
    stuIdnumber?: string,
    stuPhone?: string
  } | null>(null);

  // 处理输入框变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setSearchParams(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 重置搜索
  const handleResetSearch = () => {
    setSearchParams({ stuName: '', stuIdnumber: '', stuPhone: '' });
    setCurrentSearch(null);
    fetchStudents(1, pageSize);
  }

  useEffect(() => {
    // 获取本地存储数据
    setToken(localStorage.getItem('token'));
    const tid = localStorage.getItem("tid");
    const pl = localStorage.getItem("parentLevel");
    if (tid) setId(tid);
    if (pl === "1") setShowOrderButton(true);
    else setShowOrderButton(false);
  }, []);

  // 获取学生数据，包含搜索参数
  const fetchStudents = async (page: number, size: number, search?: { stuName?: string, stuIdnumber?: string, stuPhone?: string }) => {
    try {
      setLoading(true);
      const tid = id;
      if (!tid) throw new Error('未找到用户ID');

      // 构建查询参数，包含搜索条件
      let queryParams = `teacherId=${tid}&currPage=${page}&pageSize=${size}`;
      if (search) {
        if (search.stuName) queryParams += `&stuName=${search.stuName}`;
        if (search.stuIdnumber) queryParams += `&stuIdnumber=${search.stuIdnumber}`;
        if (search.stuPhone) queryParams += `&stuPhone=${search.stuPhone}`;
        setCurrentSearch(search); // 保存当前搜索条件
      } else {
        setCurrentSearch(null); // 清除搜索条件
      }

      const response = await fetch(
        `${API_CONFIG.BASE_URL}/api/student/personal/list?${queryParams}`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          credentials: 'include',
        }
      );

      if (!response.ok) throw new Error('获取数据失败');

      const data: ApiResponse = await response.json();
      setStudents(data.list);
      setTotal(data.total);
      setPages(data.pages);
      setCurrentPage(data.pageNum);
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setLoading(false);
    }
  }

  // 页面加载时获取数据，只在必要时重新加载
  useEffect(() => {
    if (id && token) {
      // 初始加载或搜索条件变化时加载数据
      fetchStudents(currentPage, pageSize, currentSearch);
    }
  }, [id, token, currentPage, pageSize, currentSearch]);

  // 处理分页变化，使用当前搜索条件
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  }

  // 处理搜索，使用当前搜索参数并重置到第一页
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    fetchStudents(1, pageSize, searchParams);
  }

  const handleViewOrder = (studentId: string) => {
    router.push(`/teaquery/dailiquery/stuquery/stuquery1/dingdan?stuId=${studentId}`);
  };

  // 导出函数，包含搜索条件
  const handleExport = async () => {
    try {
      const tid = id;
      if (!tid) throw new Error('未找到教师ID');

      const token = localStorage.getItem('token');
      if (!token) throw new Error('未找到认证令牌');

      let exportParams = `teacherId=${tid}`;
      if (searchParams.stuName) exportParams += `&stuName=${searchParams.stuName}`;
      if (searchParams.stuIdnumber) exportParams += `&stuIdnumber=${searchParams.stuIdnumber}`;
      if (searchParams.stuPhone) exportParams += `&stuPhone=${searchParams.stuPhone}`;

      const response = await fetch(
        `${API_CONFIG.BASE_URL}/api/student/export?${exportParams}`,
        {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          credentials: 'include',
        }
      );

      if (!response.ok) throw new Error('导出失败');

      // 处理文件下载
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `学生数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (err) {
      setError(err instanceof Error ? err.message : '导出过程中发生错误');
    }
  };

  return (
    <main className="min-h-screen bg-gray-50">
      <section className="py-4 md:py-8">
        <div className="container mx-auto px-2 sm:px-4 lg:px-6">
          <div className="bg-white rounded-lg shadow-sm overflow-hidden">
            {/* 标题和操作按钮区域 */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center p-4 md:p-6 border-b">
              <Link
                href={`/teaquery`}
                className="mr-3 p-1 rounded-md hover:bg-gray-100"
                title="返回"
              >
                {/* <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="h-6 w-6 text-gray-500"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M10 19l-7-7m0 0l7-7m-7 7h18"
                  />
                </svg> */}
              </Link>
              <h2 className="text-xl md:text-2xl font-bold text-gray-800 mb-2 md:mb-0">学生报名信息查询</h2>
              <div className="flex space-x-2 w-full md:w-auto">
                <button
                  className="px-3 py-2 md:px-4 md:py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm md:text-base w-full md:w-auto"
                  onClick={handleExport}
                >
                  导出Excel
                </button>
              </div>
            </div>
            {/* 搜索筛选区域 */}
            <div className="p-4 border-b">
              {/* <h2 className="text-xl md:text-2xl font-bold text-gray-800 mb-4">学生报名信息查询</h2> */}
              <form className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6" onSubmit={handleSearch}>
                {/* 姓名搜索框 */}
                <div className="space-y-1">
                  <label className="block text-sm font-medium text-gray-700">姓名</label>
                  <div className="relative rounded-md shadow-sm">
                    <input
                      type="text"
                      name="stuName"
                      value={searchParams.stuName}
                      onChange={handleInputChange}
                      className="block w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition duration-150 ease-in-out"
                      placeholder="请输入姓名"
                    />
                  </div>
                </div>

                {/* 身份证号搜索框 */}
                <div className="space-y-1">
                  <label className="block text-sm font-medium text-gray-700">身份证号</label>
                  <div className="relative rounded-md shadow-sm">
                    <input
                      type="text"
                      name="stuIdnumber"
                      value={searchParams.stuIdnumber}
                      onChange={handleInputChange}
                      className="block w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition duration-150 ease-in-out"
                      placeholder="请输入身份证号"
                    />
                  </div>
                </div>

                {/* 联系电话搜索框 */}
                <div className="space-y-1">
                  <label className="block text-sm font-medium text-gray-700">联系电话</label>
                  <div className="relative rounded-md shadow-sm">
                    <input
                      type="text"
                      name="stuPhone"
                      value={searchParams.stuPhone}
                      onChange={handleInputChange}
                      className="block w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm transition duration-150 ease-in-out"
                      placeholder="请输入联系电话"
                    />
                  </div>
                </div>

                {/* 搜索和重置按钮 */}
                <div className="flex items-end space-x-3">
                  <button
                    type="submit"
                    className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 text-sm font-medium transition duration-150 ease-in-out"
                  >
                    {/* <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                    </svg> */}
                    搜索
                  </button>
                  <button
                    type="button"
                    onClick={handleResetSearch}
                    className="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 text-sm font-medium transition duration-150 ease-in-out"
                  >
                    {/* <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg> */}
                    重置
                  </button>
                </div>
              </form>
            </div>

            {/* 加载状态和错误提示 */}
            {loading && (
              <div className="p-4 text-center">
                <div className="inline-flex items-center justify-center h-8 w-8 rounded-full border-4 border-blue-500 border-t-transparent animate-spin">
                  <span className="sr-only">加载中...</span>
                </div>
                <p className="mt-2 text-sm text-gray-500">正在加载数据，请稍候...</p>
              </div>
            )}

            {error && (
              <div className="p-4 bg-red-50 border border-red-200 rounded-md">
                <div className="flex items-center">
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-red-500 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <p className="text-red-700 text-sm">{error}</p>
                </div>
              </div>
            )}

            {/* 数据表格 */}
            {!loading && !error && (
              <>
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">序号</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">身份证号</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工作单位</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系电话</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">省份</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">市区</th>
                        <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {students.length === 0 ? (
                        <tr>
                          <td colSpan={8} className="px-4 py-12 text-center text-gray-500">
                            <div className="flex flex-col items-center">
                              <svg xmlns="http://www.w3.org/2000/svg" className="h-12 w-12 text-gray-400 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 012-2h2a2 2 0 012 2v6a2 2 0 01-2 2H9a2 2 0 01-2-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                              </svg>
                              <p>暂无符合条件的学生数据</p>
                            </div>
                          </td>
                        </tr>
                      ) : (
                        students.map((student, index) => (
                          <tr key={student.id} className="hover:bg-gray-50 transition-colors duration-150">
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                              {(currentPage - 1) * pageSize + index + 1}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
                              {student.stuName}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                              {student.stuIdnumber}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                              {student.workplace}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                              {student.stuPhone}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                              {student.region}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                              {student.city}
                            </td>
                            <td className="px-4 py-3 whitespace-nowrap text-sm">
                              {showOrderButton && (
                                <button
                                  className="text-blue-600 hover:text-blue-900 text-xs md:text-sm font-medium transition-colors duration-150"
                                  onClick={() => handleViewOrder(student.id)}
                                >
                                  查看订单
                                </button>
                              )}
                            </td>
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>

                {/* 分页 */}
                {students.length > 0 && (
                  <div className="px-4 py-3 bg-white border-t border-gray-200 sm:px-6">
                    <div className="flex flex-col sm:flex-row items-center justify-between">
                      <div className="text-sm text-gray-500 mb-2 sm:mb-0">
                        显示 <span className="font-medium">{(currentPage - 1) * pageSize + 1}</span> 到{' '}
                        <span className="font-medium">{(currentPage - 1) * pageSize + students.length}</span> 条，共{' '}
                        <span className="font-medium">{total}</span> 条记录
                      </div>
                      <div className="flex space-x-1">
                        <button
                          className="px-3 py-1.5 border border-gray-300 rounded-md text-sm disabled:opacity-50 bg-white text-gray-700 hover:bg-gray-50 transition-colors duration-150"
                          disabled={currentPage === 1}
                          onClick={() => handlePageChange(currentPage - 1)}
                        >
                          {/* <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                          </svg> */}
                          上一页
                        </button>
                        {Array.from({ length: Math.min(pages, 5) }, (_, i) => {
                          let pageNum = i + 1
                          if (pages > 5) {
                            if (currentPage <= 3) {
                              pageNum = i + 1
                            } else if (currentPage >= pages - 2) {
                              pageNum = pages - 4 + i
                            } else {
                              pageNum = currentPage - 2 + i
                            }
                          }
                          return (
                            <button
                              key={pageNum}
                              className={`px-3 py-1.5 border border-gray-300 rounded-md text-sm ${currentPage === pageNum
                                ? 'bg-blue-600 text-white border-blue-600'
                                : 'bg-white text-gray-700 hover:bg-gray-50'
                                } transition-colors duration-150`}
                              onClick={() => handlePageChange(pageNum)}
                            >
                              {pageNum}
                            </button>
                          )
                        })}
                        <button
                          className="px-3 py-1.5 border border-gray-300 rounded-md text-sm bg-white text-gray-700 hover:bg-gray-50 transition-colors duration-150"
                          disabled={currentPage === pages}
                          onClick={() => handlePageChange(currentPage + 1)}
                        >
                          下一页
                          {/* <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                          </svg> */}
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </section>
    </main>
  )
}

export default function CertificatesPage() {
  return (
    <Suspense fallback={<div className="py-20 text-center">
      <div className="inline-flex items-center justify-center h-8 w-8 rounded-full border-4 border-blue-500 border-t-transparent animate-spin"></div>
      <p className="mt-2 text-sm text-gray-500">加载中...</p>
    </div>}>
      <FormContent />
    </Suspense>
  );
}